package com.codejiwei.core.graphx

import org.apache.spark.SparkContext
import org.apache.spark.graphx.{Edge, EdgeDirection, Graph}

object GraphX_CollectNeighbors {
  def main(args: Array[String]): Unit = {

    // 创建 SparkContext
    val sc = new SparkContext("local", "GraphCollectNeighborsExample")

    // 创建一个简单的图
    val vertices = sc.parallelize(Array((1L, "Alice"), (2L, "Bob"), (3L, "Charlie"), (4L, "David")))
    val edges = sc.parallelize(Array(
      Edge(1L, 2L, 3), // 边1: Alice -> Bob，权重为3
      Edge(1L, 2L, 2), // 边2: Alice -> Bob，权重为2
      Edge(1L, 3L, 1), // 边3: Alice -> Charlie，权重为1
      Edge(2L, 3L, 4), // 边4: Bob -> Charlie，权重为4
      Edge(3L, 4L, 5), // 边5: Charlie -> David，权重为5
      Edge(3L, 4L, 6) // 边6: Charlie -> David，权重为6
    ))

    val graph: Graph[String, Int] = Graph(vertices, edges, "default")

    // 收集每个顶点的邻居顶点及其属性，出边方向
    val neighbors = graph.collectNeighbors(EdgeDirection.Out)

    // 输出结果
    neighbors.collect().foreach { case (vertexId, neighborArray) =>
      println(s"Vertex $vertexId's neighbors:")
      neighborArray.foreach { case (neighborId, neighborAttr) =>
        println(s"  Neighbor: $neighborId, Attribute: $neighborAttr")
      }
    }



  }
}
